﻿#ifndef DBHELPER
#define DBHELPER

#include <QSqlDatabase>
#include <QSqlQuery>
#include <QString>
#include <QStandardPaths>
#include <QFile>
#include <QSqlError>
#include <QDebug>

#define DB_FILE "/QVertex/diary.db"

static QString DOC_PATH=
        QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);

static bool openDB()
{
    QSqlDatabase db=QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName(DOC_PATH + DB_FILE);
    if(!db.open())
    {
        qDebug() << db.lastError().text();
        return false;
    }
    else
        return true;
}

static bool createDiary()
{
    if(!openDB())
        return false;
    else
    {
        QSqlQuery query;
        QString sql="create table diary (date text,"
                    "title text,"
                    "content text,"
                    "uid text primary key)";

        if(!query.exec(sql))
        {
            qDebug() << query.lastError().text();
            return false;
        }
        else
            return true;
    }
}

static bool detectDB()
{
    QFile file(DOC_PATH + DB_FILE);
    if(!file.exists())
        return createDiary();
    else
        return openDB();
}

#endif // DBHELPER

